import { Footer } from '@/components';
import {
  AlipayCircleOutlined,
  LockOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
  UploadOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, Link, useModel, history } from '@umijs/max';
import {
  Alert,
  App,
  Form,
  Select,
  Tabs,
  InputNumber,
  Switch,
  Slider,
  Radio,
  Checkbox,
  Rate,
  Upload,
  Button,
  ColorPicker,
  Space,
  Row,
  Col, message, Card, Divider, Spin, Result, Modal
} from 'antd';
import { createStyles } from 'antd-style';
import React, { useEffect, useState } from 'react';
import {
  genChartByAiAsyncUsingPost,
  genChartByAiUsingPost,
  listChartByPageUsingPost,
  getChartByIdUsingGet
} from "@/services/yubi/chartController";
import TextArea from "antd/es/input/TextArea";
import { undefined } from "@umijs/utils/compiled/zod";
import { useForm } from "antd/es/form/Form";
import ReactECharts from "echarts-for-react";

const { Option } = Select;

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

/**
 * 添加图表页面
 * @constructor
 */
const AddChartAsync: React.FC = () => {

  const [form] = useForm();

  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  // const {message} = App.useApp();
  const [chart, setChart] = useState<API.BiResponse>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [option, setOption] = useState<any>();
  const [showResult, setShowResult] = useState<boolean>(false);
  // 添加任务ID状态
  const [taskId, setTaskId] = useState<string | undefined>(undefined);

  // 添加轮询状态
  const [polling, setPolling] = useState<boolean>(false);

  const options = {
    grid: { top: 8, right: 8, bottom: 24, left: 36 },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line',
        smooth: true,
      },
    ],
    tooltip: {
      trigger: 'axis',
    },
  };

  /**
   * 提交表单
   * @param values
   */
  const onFinish = async (values: any) => {
    //避免重复提交
    if (submitting) {
      return;
    }
    setSubmitting(true);
    setShowResult(false);

    //对接后端，上传数据
    const params = {
      ...values,
      file: undefined
    };
    try {
      const res = await genChartByAiAsyncUsingPost(params, {}, values.file?.file?.originFileObj);
      console.log(res);
      if (!res?.data) {
        message.error("分析失败");
      } else {
        message.success("分析任务提交成功");
        setChart(res.data);
        // 使用 toString() 方法确保大整数不会出现精度丢失
        setTaskId(res.data.chartId?.toString()); // ✅ 修复可能的精度丢失问题
        if (res.data.genChart) {
          setOption(JSON.parse(res.data.genChart));
        }
        setShowResult(true);
        // 开始轮询
        setPolling(true);
      }
    } catch (e: any) {
      message.error("分析失败" + e.message);
    }
    setSubmitting(false);
  };

  // 添加轮询函数
  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (polling && taskId) {
      intervalId = setInterval(async () => {
        try {
          // 使用 taskId 查询图表状态
          const res = await getChartByIdUsingGet({ id: taskId });
          if (res.data && res.data.status === 'succeed') {
            setChart(res.data);
            if (res.data.genChart) {
              setOption(JSON.parse(res.data.genChart));
            }
            setPolling(false);
          } else if (res.data && res.data.status === 'failed') {
            message.error('图表生成失败');
            setPolling(false);
          }
        } catch (e: any) {
          message.error('获取任务状态失败: ' + e.message);
          setPolling(false);
        }
      }, 2000); // 每2秒查询一次
    }

    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [polling, taskId]);

  // 添加缺失的normFile函数
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const handleToMyChart = () => {
    history.push('/my_chart');
  };

  const handleContinueSubmit = () => {
    form.resetFields();
    setChart(undefined);
    setOption(undefined);
    setShowResult(false);
    setTaskId(undefined);
    setPolling(false);
  };

  const handleWaitResult = () => {
    // 什么都不做，留在当前页面
    setShowResult(true);
  };

  return (
    <div className="add-chart-async">
      <Row gutter={24}>
        <Col span={12}>
          <Card title={"智能分析表单"}>
            {showResult ? (
              <Result
                status="success"
                title="图表分析任务提交成功"
                subTitle="您可以选择以下操作"
                extra={[
                  <Button type="primary" key="wait" onClick={handleWaitResult}>
                    在此等待结果
                  </Button>,
                  <Button key="myChart" onClick={handleToMyChart}>
                    我的图表页面
                  </Button>,
                  <Button key="continue" onClick={handleContinueSubmit}>
                    继续提交新任务
                  </Button>
                ]}
              />
            ) : (
              <Form
                name="addChart"
                form={form}
                labelAlign="left"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 16 }}
                onFinish={onFinish}
                initialValues={{}}
              >
                <Form.Item name="goal" label="分析目标" rules={[{ required: true, message: '请输入分析目标' }]}>
                  <TextArea placeholder="请输入你的分析需求.... 比如网站用户分析" />
                </Form.Item>

                <Form.Item name="name" label="图表名称">
                  <TextArea placeholder="请输入你的图表名称....  比如网站用户增长图" />
                </Form.Item>
                <Form.Item
                  name="chartType"
                  label="图表类型"
                  hasFeedback
                >
                  <Select options={[
                    { value: '折线图', label: '折线图' },
                    { value: '柱状图', label: '柱状图' },
                    { value: '堆叠图', label: '堆叠图' },
                    { value: '饼图', label: '饼图' },
                    { value: '雷达图', label: '雷达图' },
                  ]} />
                </Form.Item>

                <Form.Item
                  name="file"
                  label="原始数据"
                >
                  <Upload name="file" maxCount={1}>
                    <Button icon={<UploadOutlined />}>请上传要分析的数据文件</Button>
                  </Upload>
                </Form.Item>

                <Form.Item wrapperCol={{ span: 12, offset: 5 }}>
                  <Space>
                    <Button type="primary" htmlType="submit" loading={submitting} disabled={submitting}>
                      提交
                    </Button>
                    <Button htmlType="reset">重置</Button>
                  </Space>
                </Form.Item>
              </Form>
            )}
          </Card>
        </Col>
        <Col span={12}>
          <Card title={"智能分析结果"}>
            {showResult ? (
              <>
                {chart?.genResult ?? <div>请稍后，分析结果生成中...</div>}
              </>
            ) : (
              <div>请先在左侧提交分析任务</div>
            )}
            <Spin spinning={submitting || polling} />
          </Card>
          <Divider />
          <Card title={"生成的图表"}>
            {showResult ? (
              option ? <ReactECharts option={option} /> : <div>图表生成中，请稍后...</div>
            ) : (
              <div>请先在左侧提交分析任务</div>
            )}
            <Spin spinning={submitting || polling} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};
export default AddChartAsync;
